<template>
	<div class="page-follow-plan">
		<div class="top">
            <!-- 'templateFollowList','typeFollowList' -->
			<Row :gutter="10">
				<Col :span="4">
					<Input v-model="keyWord" placeholder="输入会员卡号/姓名/手机号码" />
				</Col>
				<Col :span="4">
					<Select placeholder="全部患者类型" v-model="customerType">
						<Option
							v-for="item in diseaseTypeList"
							:value="item.id"
							:key="item.value"
						>{{ item.itemValue }}</Option>
					</Select>
				</Col>
                <Col :span="4">
					<Select v-model="selectTags" multiple placeholder="全部患者标签">
						<Option v-for="item in tagList" :value="item.id" :key="item.id">{{ item.tagName }}</Option>
					</Select>
				</Col>
				<Col :span="8">
					<Button class="ml20" type="primary" @click="search">查询</Button>
					<Button class="ml20" type="default" plain @click="reset">清空</Button>
				</Col>
				<Col :span="4" type="flex" align="right">
					<Button type="primary" @click="updateBatch">批量计划</Button>
				</Col>
			</Row>
		</div>

		<Drawer class="drawer" :title="isBatch?'批量健康随访':'健康随访'" v-model="showDrawer" :width="720" :mask-closable="false">
			<Form class="form" :model="editedItem" :rules="rules">
			    <b v-if="isBatch===false" class="lh200">随访信息</b>
				<Row :gutter="10" v-if="isBatch===false">
                    <Col :span="12">
                        <FormItem class="plain" label="姓名" label-position="left">
                            <span>{{curCustomer.customerName}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="出生年月" label-position="left">
                            <span>{{curCustomer.birthday | YMD}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="性别" label-position="left">
                            <span v-if="Number(curCustomer.sex)===1">男</span>
                            <span v-else-if="Number(curCustomer.sex)===2">女</span>
                            <span v-else>-</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="手机号码" label-position="left">
                            <span>{{curCustomer.mobile}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="身份证号" label-position="left">
                            <span>{{curCustomer.customerInfo.idCard}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="档案编号" label-position="left">
                            <span>{{editedItem.customerFileNumber}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="身高(cm)" label-position="left">
                            <span>{{curCustomer.customerInfo.height}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="体重(kg)" label-position="left">
                            <span>{{curCustomer.customerInfo.weight}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="BMI指数" label-position="left">
                            <span>{{bmi}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="患者类型" label-position="left">
							<span>{{getCustomerType({customerType:curCustomer.customerInfo.diseaseType})}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="确诊时间" label-position="left">
                            <span>{{editedItem.addTime}}</span>
                        </FormItem>
                    </Col>
                    <Col :span="12">
                        <FormItem class="plain" label="并发症" label-position="left">
                            <span>{{curCustomer.customerInfo.complication}}</span>
                        </FormItem>
                    </Col>
				</Row>
				<Row :gutter="10" v-if="isBatch">
					<Col :span="12">
                        <FormItem label="随访患者:" label-position="left">
                            <Select multiple v-model="selection" placeholder="请选择一名或多名患者">
                                <Option
                                    class="select"
                                    v-for="item in items"
                                    :value="item.id"
                                    :key="item.id"
                                >{{ item.customerName }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
				</Row>
				<Divider v-if="isBatch===false" />

			    <b v-if="isBatch===false" class="lh200">随访信息</b>
				<Row type="flex" :gutter="20">
					<Col :span="12">
						<FormItem label="计划人员" label-position="left">
							<Select v-model="editedItem.planUserId" class="cube" placeholder="请选择计划人员">
								<Option
									class="select"
									v-for="item in userList"
									:value="item.id"
									:key="item.id"
								>{{ item.username }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem label="随访模板" label-position="left">
							<Select v-model="editedItem.templateId" class="cube" @on-change="templateIdChange" placeholder="请选择随访模板">
								<Option
									class="select"
									v-for="item in templateFollowList"
									:value="item.id"
									:key="item.id"
								>{{ item.templateName }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem label="随访类型" label-position="left">
							<Select v-model="editedItem.followType" @on-change="followTypeChange" class="cube" placeholder="请选择随访类型">
								<Option
									class="select"
									v-for="item in typeFollowList"
									:value="item.id"
									:key="item.id"
								>{{ item.itemValue }}</Option>
							</Select>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem label="计划时间" label-position="left">
							<DatePicker
								class="time-picker"
                                @on-change="t => editedItem.planTime=t"
								:value="editedItem.planTime"
								type="datetime"
								placeholder="请选择计划时间"
							/>
						</FormItem>
					</Col>
					<Col :span="24">
						<FormItem label="随访内容" label-position="left" prop="followContent">
							<Input class="cube" type="textarea" v-model="editedItem.followContent" placeholder />
						</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" @click="save" :loading="editedIndex===-1?createLoading:updateLoading">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
					@on-selection-change="tableSelectionchange"
				>
					<template slot-scope="{ row }" slot="addTime">
						<span>{{row.addTime | YMDHMS}}</span>
					</template>
                    <template slot-scope="{ row }" slot="birthday">
						<span>{{row.birthday | AGE}}</span>
					</template>

					<template slot-scope="{ row }" slot="customerType">
						<span>{{getCustomerType(row)}}</span>
					</template>
					<template slot-scope="{ row }" slot="sex">
						<span v-if="Number(row.sex)===1">男</span>
						<span v-else-if="Number(row.sex)===2">女</span>
						<span v-else>-</span>
					</template>
					<template slot-scope="{row}" slot="action">
                        <router-link class="mr10" :to="{path: '/customer/detail',query:{id:row.id}}">档案</router-link>
                        <a href="javascript:;" @click="create(row)">制定计划</a>
					</template>
				</Table>
				
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>

import { customerPageQueryList, customerGet } from '@api/customer.js'
import { followAdd, followBatchAdd } from '@api/follow.js'
import { mapState } from '@lib/x_.js'
export default {
	data() {
		return {
			rules: {
				interventionContent: [{ required: true, message: '请输入随访内容', trigger: 'blur' }, { type: 'string', min: 6, message: '最少6个字符', trigger: ['blur', 'change'] }]
            },
            bmi: '',
			showDrawer: false,
			loading: false,
			updateLoading: false,
			createLoading: false,
			editedIndex: -1,
            curCustomer: {
				birthday: '',
				customerInfo: {
					idCard: '',
					careTime: ''
				}
			},
			editedItem: {
				templateId: '',
				followType: '',
				customerId: '',
				followContent: '',
				planTime: '',
				planUserId: '',

			},
			defaultItem: {
				templateId: '',
				followType: '',
				customerId: '',
				followContent: '',
				planTime: '',
				planUserId: '',
			},
			showTimePicker: false,
			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			tableColumns: [
				{
					width: 60,
					type: 'selection'
				},
				{
					title: '档案编号',
					width: 130,
					align: 'left',
					key: 'customerFileNumber'
				},
				{
					title: '姓名',
					align: 'left',
					width: 130,
					key: 'customerName'
				},

				{
					title: '性别',
					align: 'left',
					width: 130,
					slot: 'sex'
				},
				{
					title: '年龄',
					align: 'left',
				    slot: 'birthday',
					width: 130,
				},
				{
					title: '患者类型',
					align: 'left',
					slot: 'customerType',
					width: 130,
				},
				{
					title: '患者标签',
					align: 'left',
					key: 'tags',
					width: 220
				},
				{
					title: '手机号码',
					align: 'left',
					key: 'mobile',
					width: 120
				},
				{
					title: '最近随访时间',
					slot: 'addTime',
					align: 'left',
					width: 170
				},
				{
					title: '操作',
					slot: 'action',
					align: 'left',
					width: 200,
					align: 'left',
                },
                {
					title: ' ',
					key: '',
					align: '',
				}
			],

			daterange: ['', ''],
			customerType: '',
			keyWord: '',
            selectTags: [],
			selection: [],
			isBatch: false,
		}
	},
	mounted() {
		this.customerPageQueryList()
	},
	computed: {
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
        },
        ...mapState(['templateFollowList','typeFollowList','diseaseTypeList','familyList','diseaseHistoryList','familyHistoryList','nowTreatmentList','tagList','userList']),
    },
	methods: {
        templateIdChange(id){
            const idx = this.templateFollowList.findIndex((item,i) => item.id === id)
            if (idx > -1) {
                const { id,templateContent,templateType } = this.templateFollowList[idx];
                const idx1 = this.typeFollowList.findIndex((item,i) => item.itemKey === templateType)
                if (idx1 > -1) {
                    const { id } = this.typeFollowList[idx1]
                    this.editedItem.followType = id;
                } else {
                    this.editedItem.followType = "";
                }
                this.editedItem.followContent = templateContent;
                this.editedItem.templateId = id;
            } else {
                this.editedItem.followContent = "";
                this.editedItem.templateId = "";
            }
        },
        followTypeChange(id){
            const idx = this.typeFollowList.findIndex((item,i) => item.id === id)
            console.log("idx>", idx)
            if (idx<=-1) {
                this.editedItem.followContent = ""
                this.editedItem.templateId = "";
            }
            const { itemKey,  } = this.typeFollowList[idx]
            const idx1 = this.templateFollowList.findIndex((item,i) => item.templateType===itemKey)
            if (idx1 > -1) {
                const { templateContent,id } = this.templateFollowList[idx1]
                this.editedItem.followContent = templateContent;
                this.editedItem.templateId = id;
            } else {
                this.editedItem.followContent = ""
                this.editedItem.templateId = "";
            }
        },
		getCustomerType(row) {
			const { customerType } = row
			const { diseaseTypeList } = this
			const idx = diseaseTypeList.findIndex((item, i) => String(item.itemKey) === customerType)
			if (idx > -1) {
				return diseaseTypeList[idx]['itemValue']
			} else {
				return ''
			}
		},
		search() {
			this.page = 1
			this.pageSize = 20
			this.customerPageQueryList()
		},
		reset() {
			this.page = 1
			this.pageSize = 20
			this.customerType = ''
            this.keyWord = ''
            this.selectTags = []
			this.daterange = ['', '']
		},
		radioChange() {
			console.log('radioChange')
		},
		tableSelectionchange(selection) {
			selection.map((item, i) => (selection[i] = item.id))
			this.selection = selection
		},
		updateBatch() {
            if (this.selection.length===0) {
                return this.$Message.error('请选择患者')
            }
			this.create()
			this.isBatch = true
		},
		pageChange(page) {
			this.page = page
			this.customerPageQueryList()
		},
		update(item) {
			const { id } = item
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
            this.showDrawer = true

            console.log("update")
            customerGet({ id: item.customerId }).then(res => {
                if (res.code === '0') {
                    this.curCustomer = res.data;
                    const { customerInfo } = this.curCustomer;
                    const { weight, height } = customerInfo || {}
                    console.log
                    if (weight && height) {
                        try {
                            this.bmi = Math.floor(Number(weight) /(Number(height) * Number(height)) * 10000);
                            console.log('this.bmi-->' ,this.bmi)
                        } catch (error) {
                            console.log('catch')
                        }
                    }

                } else {
                    this.modal(res, '获取患者信息')
                }
            })
		},
		create(row) {
			this.editedIndex = -1
			if (row) {
                this.isBatch = false
                this.bmi = '';
				customerGet({ id: row.id }).then(res => {
					if (res.code === '0') {
                        this.curCustomer = res.data;
                        const { curCustomer, customerInfo } = this.curCustomer.customerInfo;
                        const { weight, height } = customerInfo || {}
                        if (weight && height) {
                            try {
                                this.bmi = Math.floor(Number(weight) /(Number(height) * Number(height)) * 10000);
                                console.log('this.bmi-->' ,this.bmi)
                            } catch (error) {
                                console.log('catch')
                            }
                        }

					} else {
						this.modal(res, '获取患者信息')
					}
                })
                this.update(row)
			} else {
				this.editedItem = Object.assign({}, this.defaultItem)
			}
			this.showDrawer = true
		},
		remove(item, idx) {
			//done this.close();
		},
		async save() {
			if (this.isBatch) {
				const { selection } = this
                const { templateId, followType, followContent, planTime, planUserId } = this.editedItem
                if (!templateId) {
                    return this.$Message.error('请选择模板')
                }
                if (!followType) {
                    return this.$Message.error('请选择类型')
                }
                if (!followContent) {
                    return this.$Message.error('请输入内容')
                }
                if (selection.length===0) {
                    return this.$Message.error('请选择患者')
                }
                if (!planTime) {
                    return this.$Message.error('请选择计划时间')
                }

				this.createLoading || (this.createLoading = true)
				const res = await followBatchAdd({
					customerIds: selection,
					templateId,
					followType,
					followContent,
					planTime,
					planUserId
				})
				this.createLoading = false
				this.modal(res, '批量随访')
				return
			} else {
                if (this.editedIndex > -1) {
                    const { id, templateId, followType, followContent, planTime, planUserId } = this.editedItem

                    if (!templateId) {
                        return this.$Message.error('请选择模板')
                    }
                    if (!followType) {
                        return this.$Message.error('请选择类型')
                    }
                    if (!followContent) {
                        return this.$Message.error('请输入内容')
                    }
                    
                    if (!planTime) {
                        return this.$Message.error('请选择计划时间')
                    }

                
                    this.updateLoading || (this.updateLoading = true)
                    const res = await followAdd({ customerId: id, templateId, followType, followContent, planTime, planUserId })
                    this.updateLoading = false
                    this.modal(res)
                } else {
                    const { id, templateId, followType, followContent, planTime, planUserId } = this.editedItem

                    if (!templateId) {
                        return this.$Message.error('请选择模板')
                    }
                    if (!followType) {
                        return this.$Message.error('请选择类型')
                    }
                    if (!followContent) {
                        return this.$Message.error('请输入内容')
                    }
                    
                    if (!planTime) {
                        return this.$Message.error('请选择计划时间')
                    }

                    this.createLoading || (this.createLoading = true)
                    const res = await followAdd({ customerId: id, templateId, followType, followContent, planTime, planUserId })
                    this.createLoading = false
                    this.modal(res)
                }
            }
			
			this.customerPageQueryList()
		},
		modal(res, title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
				})
				this.close()
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg || '提交错误'
				})
			}
		},
		close() {
			this.showDrawer = false
			this.isBatch = false
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
		customerPageQueryList() {
			this.loading || (this.loading = true)
			const { selectTags,customerType, keyWord, daterange, page, pageSize, loading } = this
			const [beginTime, endTime] = daterange;
			customerPageQueryList({ tagList: selectTags ,beginTime, endTime, customerType, keyWord, page, pageSize })
				.then(res => {
					this.loading = false
					if (res.code === '0') {
						const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data
						this.items = items
						this.page = currentPage
						this.totalNum = totalNum
					} else {
						this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
						})
					}
				})
				.catch(err => {
					this.loading = false
				})
		}
	},
	watch: {
		showDrawer(after) {
			after || this.close()
		}
	}
}
</script>
<style scoped lang="scss">
.page-follow-plan{
    background-color: #fff;
}
.drawer {
	.ivu-select {
		width: auto;
		min-width: 250px;
	}
	.time-picker {
		min-width: 250px;
	}
	.cube {
		max-width: 600px;
	}
	.label-group {
		display: block;
	}
	.system-role {
		background-color: #fff;
	}
	.label {
		min-width: 60px;
		margin-right: 10px;
		display: inline-block;
		vertical-align: middle;
		white-space: nowrap;
		overflow: hidden;
	}
}
</style>